package com.ambitor.grass.sql.statement;

import java.sql.Connection;
import java.sql.ResultSet;

import org.apache.commons.lang.StringUtils;

import com.ambitor.grass.sql.data.Parameter;

public class DefaultParameterStatementImpl extends ParameterStatementImpl
		implements DefaultOperation {

	private Parameter param;

	public DefaultParameterStatementImpl(Connection conn, String sql,
			Parameter param) throws Exception {
		super(conn, sql);
		this.param = param;
	}

	public ResultSet executeQuery() throws Exception {
		setParameters(this.param);
		ResultSet result = this.getStatement().executeQuery();
		return result;
	}

	public int executeUpdate() throws Exception {
		setParameters(this.param);
		int result = this.getStatement().executeUpdate();
		return result;
	}

	@Override
	public String executeInsertAndReturnLastInsertId() throws Exception {
		setParameters(this.param);
		this.getStatement().executeUpdate();
		ResultSet rs = this.getStatement().getGeneratedKeys();
		String autoIncKey = "";
		if (rs.next()) {
			autoIncKey = rs.getString(1);
		}
		if (StringUtils.isBlank(autoIncKey))
			throw new Exception("获取自增主键出现异常");
		return autoIncKey;
	}
}
